package setting

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/response"
	"likeadmin/dao"
	"likeadmin/util"
)

const (
	SmsStatusOn  = 1 // 状态开启
	SmsStatusOff = 0 // 状态关闭
)

type ISmsSettingService interface {
	List() (list []resp.SmsSettingResp, e error)
	Detail(c *gin.Context, name string) (res resp.SmsSettingResp, e error)
	Edit(c *gin.Context, editReq req.SmsSettingEditReq) (e error)
}

// NewSmsSettingService 初始化
func NewSmsSettingService(db *gorm.DB, dao *dao.Query) ISmsSettingService {
	return &smsSettingService{db: db, dao: dao}
}

// smsSettingService 通知设置服务实现类
type smsSettingService struct {
	db  *gorm.DB
	dao *dao.Query
}

// List 通知设置列表
func (srv smsSettingService) List() (list []resp.SmsSettingResp, e error) {
	data, err := util.ConfigUtil.Get(srv.db, "sms")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	// 获取默认开启项
	defaultEngine, err := util.ConfigUtil.GetVal(srv.db, "sms", "default", "aliyun")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	for _, name := range data {
		if name != "" {
			var item resp.SmsSettingResp
			err = json.Unmarshal([]byte(name), &item)
			// 排除 default 值
			if err != nil {
				continue
			}

			if defaultEngine == item.Alias {
				item.Status = SmsStatusOn
			} else {
				item.Status = SmsStatusOff
			}

			list = append(list, item)
		}
	}

	return list, nil
}

// Detail 通知设置详情
func (srv smsSettingService) Detail(c *gin.Context, name string) (res resp.SmsSettingResp, e error) {
	data, err := util.ConfigUtil.GetVal(srv.db, "sms", name, "")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	// 获取默认开启项
	defaultEngine, err := util.ConfigUtil.GetVal(srv.db, "sms", "default", "aliyun")
	if e = response.CheckErr(err, "Detail Get err"); e != nil {
		return
	}

	var item resp.SmsSettingResp
	_ = json.Unmarshal([]byte(data), &item)

	if defaultEngine == item.Alias {
		item.Status = SmsStatusOn
	} else {
		item.Status = SmsStatusOff
	}

	response.Copy(&res, item)

	return
}

// Edit 通知设置编辑
func (srv smsSettingService) Edit(c *gin.Context, editReq req.SmsSettingEditReq) (e error) {

	// 设置开启
	if editReq.Status == SmsStatusOn {
		err := util.ConfigUtil.Set(srv.db, "sms", "default", editReq.Alias)
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}

	// 不保存状态 状态由default 的值决定
	editReq.Status = SmsStatusOff
	marshal, err := json.Marshal(editReq)
	if err != nil {
		if e = response.CheckErr(err, "Save Set name err"); e != nil {
			return
		}
	}

	err = util.ConfigUtil.Set(srv.db, "sms", editReq.Alias, string(marshal))
	if e = response.CheckErr(err, "Save Set name err"); e != nil {
		return
	}

	// 删除缓存
	util.RedisUtil.HDel("sms", "default")
	util.RedisUtil.HDel("sms", editReq.Alias)

	return
}
